package com.example.qu_tao.View;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.qu_tao.R;

public class XiugaimimaActivity extends AppCompatActivity {
    private ImageView back;
    private EditText oldPasswordInput, newPasswordInput, confirmPasswordInput;
    private Button changePasswordButton;
    private TextView passwordStrength;
    private long userId;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_denglumima);

        back = findViewById(R.id.ChangePassword_back_button);
        oldPasswordInput = findViewById(R.id.old_password_input);
        newPasswordInput = findViewById(R.id.new_password_input);
        confirmPasswordInput = findViewById(R.id.confirm_password_input);
        changePasswordButton = findViewById(R.id.change_password_button);
        passwordStrength = findViewById(R.id.password_strength);

        // 获取用户ID
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        userId = sharedPreferences.getLong("user_id", -1);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        changePasswordButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changePassword();
            }
        });

        newPasswordInput.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String newPassword = s.toString();
                showPasswordStrength(newPassword);
            }

            @Override
            public void afterTextChanged(android.text.Editable s) {}
        });
    }

    private void changePassword() {
        String oldPassword = oldPasswordInput.getText().toString();
        String newPassword = newPasswordInput.getText().toString();
        String confirmPassword = confirmPasswordInput.getText().toString();

        if (TextUtils.isEmpty(oldPassword) || TextUtils.isEmpty(newPassword) || TextUtils.isEmpty(confirmPassword)) {
            Toast.makeText(this, "请输入完整信息", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!isValidOldPassword(oldPassword)) {
            Toast.makeText(this, "当前密码输入错误", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!newPassword.equals(confirmPassword)) {
            Toast.makeText(this, "新密码和确认密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!isPasswordStrong(newPassword)) {
            Toast.makeText(this, "新密码强度不足，请至少包含字母和数字，且长度不少于8位", Toast.LENGTH_SHORT).show();
            return;
        }

        if (updatePassword(newPassword)) {
            Toast.makeText(this, "密码修改成功", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            Toast.makeText(this, "密码修改失败，请稍后重试", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean isValidOldPassword(String oldPassword) {
        Uri uri = Uri.parse("content://com.example.qu_tao.provider/user/" + userId);
        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = contentResolver.query(uri, new String[]{"user_password"}, null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            @SuppressLint("Range") String storedPassword = cursor.getString(cursor.getColumnIndex("user_password"));
            cursor.close();
            return oldPassword.equals(storedPassword);
        }

        return false;
    }

    private boolean updatePassword(String newPassword) {
        Uri uri = Uri.parse("content://com.example.qu_tao.provider/user/" + userId);
        ContentResolver contentResolver = getContentResolver();
        ContentValues values = new ContentValues();
        values.put("user_password", newPassword);

        int rowsUpdated = contentResolver.update(uri, values, null, null);
        return rowsUpdated > 0;
    }

    private void showPasswordStrength(String password) {
        String strength;
        if (isPasswordStrong(password)) {
            strength = "密码强度: 强";
            passwordStrength.setTextColor(getResources().getColor(R.color.success));
        } else {
            strength = "密码强度: 弱";
            passwordStrength.setTextColor(getResources().getColor(R.color.error));
        }
        passwordStrength.setText(strength);
        passwordStrength.setVisibility(View.VISIBLE);
    }

    private boolean isPasswordStrong(String password) {
        return password.matches("^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$");
    }
}